package com.lf.freezingpoint.common.security.filter;

import com.alibaba.fastjson2.JSON;
import com.lf.freezingpoint.common.entity.Claims;
import com.lf.freezingpoint.common.entity.R;
import com.lf.freezingpoint.common.security.handler.JWTAuthenticationEntryPoint;
import com.lf.freezingpoint.common.util.JWTUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.logging.Logger;

/**
 * 自定义jwt全局过滤器
 * <p>
 * 1.没有携带token放行
 * 2.携带token,将用户信息添加至security上下文中
 */
@Component
public class JWTAuthenticationFilter extends OncePerRequestFilter {
    private static final Logger logger = Logger.getLogger(JWTAuthenticationFilter.class.toString());
    @Autowired
    private JWTAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取当前请求的uri
        String uri = request.getRequestURI();
        logger.info("请求路径:" + uri);
        //判断是否是认证请求路径
        //是：直接放行
        if (uri.endsWith("/api/login") || uri.endsWith("/api/logout") || uri.startsWith("/swagger-ui") || uri.startsWith("/v3/api-docs") || uri.startsWith("/favicon.ico")) {
            filterChain.doFilter(request, response);
            return;
        }

        //否：获取请求头中携带的token
        String authorization = request.getHeader("Authorization");
        logger.info("携带authorization:" + authorization);

        //判断是否携带token
        //否：抛出异常
        if (StringUtils.isBlank(authorization)) {
            jwtAuthenticationEntryPoint.commence(request, response, new AuthenticationServiceException("token无效"));
            return;
        }

        String realToken = authorization.replace("Bearer ", "");
        if (redisTemplate.hasKey(realToken)) {
            jwtAuthenticationEntryPoint.commence(request, response, new AuthenticationServiceException("token无效"));
            return;
        }

        //是：校验jwt有效性
        R r = JWTUtil.verifyToken(realToken);
        if (R.isError(r)) {
            jwtAuthenticationEntryPoint.commence(request, response, new AuthenticationServiceException(r.getMsg()));
            return;
        }

        Claims claims = (Claims) r.getData();
        String username = claims.getUsername();

        //认证
        //通过用户名，从redis中返回用户信息
        UserDetails userDetails = JSON.parseObject((String) redisTemplate.opsForValue().get(username), UserDetails.class);
        if (ObjectUtils.isEmpty(userDetails)) {
            jwtAuthenticationEntryPoint.commence(request, response, new AuthenticationServiceException("token无效"));
            return;
        }
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(realToken, "", userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

        filterChain.doFilter(request, response);
    }
}
